package com.coolxiaoyao.web.context;

import com.coolxiaoyao.common.context.AbstractNtApplicationContext;
import com.coolxiaoyao.common.http.HttpMethod;
import com.coolxiaoyao.common.inner.UrlInnerExchange;
import com.coolxiaoyao.common.mapping.UrlMapping;

import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Kerry on 18/09/20
 */

public class NtWebApplicationContext extends AbstractNtApplicationContext {


    @Override
    protected void beforeContainerInit(String[] args, Object[] primaryClass) {
    }

    @Override
    protected void afterContainerInit(String[] args, Object[] primaryClass) {

    }

    @Override
    public UrlInnerExchange matchUrlMapping(String url) {
        if (urlMapping == null) {
            return null;
        }
        Map<HttpMethod, UrlMapping> httpMethodUrlMappingMap = urlMapping.get(url);
        if (httpMethodUrlMappingMap != null) {
            return new UrlInnerExchange(url, null, httpMethodUrlMappingMap);
        }
        Set<String> keySet = urlMapping.keySet();

        String findKey = null;
        for (String keyUrl : keySet) {
            Pattern pattern = Pattern.compile(keyUrl);
            Matcher matcher = pattern.matcher(url);
            if (matcher.matches()) {
                findKey = keyUrl;
                break;
            }
        }
        if (findKey != null) {
            return new UrlInnerExchange(url, findKey, urlMapping.get(findKey));
        }
        return null;
    }

}
